package com.jammingpro.blog_system.intercepter;

import com.jammingpro.blog_system.constant.Constant;
import com.jammingpro.blog_system.mapper.UserInfoMapper;
import com.jammingpro.blog_system.model.UserInfo;
import com.jammingpro.blog_system.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginIntercepter implements HandlerInterceptor {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle is working...");
        String token = request.getHeader(Constant.REQUEST_USER_TOKEN);
        if(token == null) {
            response.setStatus(401);
            return false;
        }
        Integer id = JwtUtils.getIdByToken(token);
        if(id == null) {
            response.setStatus(401);
            return false;
        }
        UserInfo userInfo = userInfoMapper.getUserInfoById(id);
        if(userInfo == null) {
            response.setStatus(401);
            return false;
        }
        log.info("success pass preHandle...");
        return true;
    }
}
